package model
{
    import flash.events.ErrorEvent;
    import flash.events.Event;
import flash.sampler.getSampleCount;

import model.service.AuthService;
    import model.vo.ConfigVO;

    import org.kolonitsky.alexey.debug.DebugWrapper;

    import org.kolonitsky.alexey.net.ElfinSerivce;
    import org.kolonitsky.alexey.utils.ArrayUtils;

    import org.puremvc.as3.patterns.proxy.Proxy;

    public class ElfinProxy extends Proxy
    {
        public static const NAME:String = "elfinProxy";
        public static const CONNECTION_ESTABLISHED:String = "connectionEstablished_elfinProxy";
        public static const CONNECTION_LOOSE:String = "connectionLoose_elfinProxy";


        //---------------------------------------------------------------------
        //
        //  Public
        //
        //---------------------------------------------------------------------

        public function get config():ConfigVO
        {
            return data as ConfigVO;
        }


        //---------------------------------------------------------------------
        //  Methods
        //---------------------------------------------------------------------

        public function ElfinProxy()
        {
            super(NAME, new ConfigVO());
            sourceHash = [];
        }

        /**
         *  Try connect to each server in source list. On first success connection
         *  other efforts is closed.
         *
         *  @param sources
         */
        public function getAuthToken(sources:Array):void
        {
            if (sources == null || sources.length == 0)
            {
                DebugWrapper.trace("ERROR: Application incorrect embedded. Please check base_url flashvar.");
                return;
            }

            for each (var host:String in sources)
            {
                var serv:AuthService = new AuthService();
                serv.baseURL = host;
                serv.addEventListener(Event.COMPLETE, authService_completeHandler);
                serv.addEventListener(ErrorEvent.ERROR, authService_errorHandler);
                serv.getAuthToken();

                sourceHash.push(serv);
            }
        }




        //---------------------------------------------------------------------
        //
        //  Private
        //
        //---------------------------------------------------------------------

        private var sourceHash:Array;

        private function getServiceIndex(service:AuthService):int
        {
            for (var i:int = 0; i < sourceHash.length; i++)
                if (sourceHash[i] == service)
                    return i;
            return -1;
        }


        //---------------------------------------------------------------------
        //  Event handler
        //---------------------------------------------------------------------

        private function authService_completeHandler(event:Event):void
        {
            var serv:AuthService = event.currentTarget as AuthService;
            DebugWrapper.trace("INFO: Application connected to " + serv.baseURL);
            config.baseUrl = serv.baseURL;
            config.authToken = serv.authToken;

            // delete all services.
            for (var i:int = 0; i < sourceHash.length; i++)
                (sourceHash[i] as ElfinSerivce).clear();
            sourceHash = [];

            sendNotification(CONNECTION_ESTABLISHED);
        }

        private function authService_errorHandler(event:ErrorEvent):void
        {
            var serv:AuthService = event.currentTarget as AuthService;
            DebugWrapper.trace("DEBUG: Connect to " + serv.baseURL + " failed");
            
            sourceHash.splice(getServiceIndex(serv), 1);

            if (sourceHash.length == 0)
                sendNotification(CONNECTION_LOOSE);
        }
        
        


    }
}
